<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>后台首页</title>
    <script src="ROOT_PATH/static/js/jquery-3.5.1.min.js"></script>
    <script src="ROOT_PATH/static/js/vue.min.js"></script>
</head>
<body>
    <textarea id="input"></textarea>
    <button onclick="sendMessage()">发送</button>
</body>
</html>

<script>
    var timeInterval = null;
    var wsUrl = 'ws://'+  window.location.hostname +':8282';
    var ws = new WebSocket(wsUrl);
    ws.onopen = function(event){
        //console.log(event, 'websocket连接成功');
        timeInterval = setInterval(function(){
            //console.log('心跳');
            ws.send('ping');
        }, 1000);
    }

    ws.onmessage = function(event){
        try{
            chat.work(JSON.parse(event.data));
        }catch(e){
            console.log(e, '出错了');
        }
    }

    ws.onclose = function(event){
        console.log(event, 'websocket连接关闭');
    }

    ws.onerror = function(event){
        console.log(event, 'websocket连接出错');
    }

    var chat = {
        work : function(data){
            if(data.type && data.data){
                if(this[data.type]){
                    this[data.type](data.data);
                }
            }
        },
        init : function(data){
            $.ajax({
                url: 'ROOT_PATH/im/kefu/bind',
                data: {
                    client_id : data.client_id,
                },
                type: "post",
                dataType: "JSON",
                success: function(res) {
                    if(res.code >= 0){
                        console.log(res.data.uid + ' 绑定成功');
                    }
                }
            });
        },
        online: function(data){
            console.log(data.uid + ' 上线了');
        },
        text: function(data){
            console.log('消息---', data.content);
        }
    };

    function sendMessage(){
        var message = $('#input').val();
        if(message){
            $.ajax({
                url: 'ROOT_PATH/im/kefu/send',
                data: {
                    message : message,
                },
                type: "post",
                dataType: "JSON",
                success: function(res) {
                    if(res.code >= 0){
                        console.log('我说---',message);
                    }
                }
            });
        }
    }
</script>